package org.ithasu.filpilote.data.entities;

import org.ithasu.tools.data.Entity;
import org.ithasu.tools.net.JSONTools;
import org.ithasu.tools.net.JSONTools.JSONContext;
import org.ithasu.tools.net.JSONTools.JSONEntity;
import org.json.simple.JSONObject;

public final class Wire implements JSONEntity, Entity {

	private final static String JSON_PROPERTY_INDEX = "index";
	private final static String JSON_PROPERTY_NAME = "name";
	private final static String JSON_PROPERTY_DEFAULT = "default";
	private final static Mode JSON_DEFAULT_MODE = Mode.COMFORT;

	private long index;
	private String name;
	private Mode defaultMode;

	public Wire(long index, String name) {
		this.index = index;
		this.name = name;
		this.defaultMode = Mode.COMFORT;
	}

	public Wire(JSONContext context, JSONObject o) {
		parseJSON(context, o);
	}

	// -- Entity ----------------------------------------

	@Override
	public final long getId() {
		return index;
	}

	// -- Properties ----------------------------------------

	public final String getName() {
		return name;
	}

	public Mode getDefaultMode() {
		return defaultMode;
	}

	public void setDefaultMode(Mode mode) {
		this.defaultMode = mode;
	}

	// -- JSON ----------------------------------------

	@Override
	public void parseJSON(JSONContext context, JSONObject o) {
		this.index = JSONTools.getProperty(Long.class, o, JSON_PROPERTY_INDEX,
				-1l);
		this.name = JSONTools.getProperty(String.class, o, JSON_PROPERTY_NAME,
				"<default wire>");
		String defaultModeName = JSONTools.getProperty(String.class, o,
				JSON_PROPERTY_DEFAULT);
		if (defaultModeName != null) {
			this.defaultMode = Mode.valueOf(defaultModeName);
		} else {
			this.defaultMode = Mode.COMFORT;
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public JSONObject toJSON(JSONContext context) {
		JSONObject o = new JSONObject();
		o.put(JSON_PROPERTY_INDEX, index);
		o.put(JSON_PROPERTY_NAME, name);
		if (defaultMode != JSON_DEFAULT_MODE) {
			o.put(JSON_PROPERTY_DEFAULT, defaultMode.name());
		}
		return o;
	}
}
